//
//  VideoViewController.m
//  BeautyBaoUnion
//
//  Created by 肖智 on 2016/10/28.
//  Copyright © 2016年 肖智. All rights reserved.
//

#import "VideoViewController.h"
#import "IDCaptureSessionAssetWriterCoordinator.h"
#import "IDFileManager.h"
#import "IDPermissionsManager.h"
@interface VideoViewController ()<IDCaptureSessionCoordinatorDelegate>
@property (nonatomic, strong) IDCaptureSessionCoordinator *captureSessionCoordinator;
@property (nonatomic, retain)  UIButton *recordButton;

@property (nonatomic, assign) BOOL recording;
@property (nonatomic, assign) BOOL dismissing;
@end

@implementation VideoViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    _recordButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _recordButton.frame = CGRectMake(0, 84, 50, 30);
    _recordButton.backgroundColor = [UIColor lightGrayColor];
    [_recordButton setTitle:@"开始" forState:UIControlStateNormal];
    [_recordButton addTarget:self action:@selector(beginAnimation) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_recordButton];
    
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.frame = CGRectMake(100, 84, 50, 30);
    btn.backgroundColor = [UIColor lightGrayColor];
    [btn setTitle:@"关闭" forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(stopAnimation) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btn];
    [self configureInterface];
    // Do any additional setup after loading the view.
}
-(void)beginAnimation{
    if(_recording){
        [_captureSessionCoordinator stopRecording];
    } else {
        // Disable the idle timer while recording
        [UIApplication sharedApplication].idleTimerDisabled = YES;
        
        self.recordButton.enabled = NO; // re-enabled once recording has finished starting
        [_recordButton setTitle:@"停止" forState:UIControlStateNormal];

        [self.captureSessionCoordinator startRecording];
        
        _recording = YES;
    }
}
-(void)stopAnimation{
    //TODO: tear down pipeline
    if(_recording){
        _dismissing = YES;
        [_captureSessionCoordinator stopRecording];
    } else {
        [self stopPipelineAndDismiss];
    }
}
- (void)checkPermissions
{
    IDPermissionsManager *pm = [IDPermissionsManager new];
    [pm checkCameraAuthorizationStatusWithBlock:^(BOOL granted) {
        if(!granted){
            NSLog(@"we don't have permission to use the camera");
        }
    }];
    [pm checkMicrophonePermissionsWithBlock:^(BOOL granted) {
        if(!granted){
            NSLog(@"we don't have permission to use the microphone");
        }
    }];
}

- (void)configureInterface
{   [self checkPermissions];
    _captureSessionCoordinator = [IDCaptureSessionAssetWriterCoordinator new];
    [_captureSessionCoordinator setDelegate:self callbackQueue:dispatch_get_main_queue()];

    AVCaptureVideoPreviewLayer *previewLayer = [_captureSessionCoordinator previewLayer];
    previewLayer.frame = CGRectInset(self.view.bounds, 50, 120);
    [self.view.layer insertSublayer:previewLayer atIndex:0];
    
    [_captureSessionCoordinator startRunning];
}

- (void)stopPipelineAndDismiss
{
    [_captureSessionCoordinator stopRunning];
    [self dismissViewControllerAnimated:YES completion:nil];
    _dismissing = NO;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
#pragma mark = IDCaptureSessionCoordinatorDelegate methods

- (void)coordinatorDidBeginRecording:(IDCaptureSessionCoordinator *)coordinator
{
    _recordButton.enabled = YES;
}

- (void)coordinator:(IDCaptureSessionCoordinator *)coordinator didFinishRecordingToOutputFileURL:(NSURL *)outputFileURL error:(NSError *)error
{
    [UIApplication sharedApplication].idleTimerDisabled = NO;
    
//    _recordButton.title = @"Record";
    [_recordButton setTitle:@"Record" forState:UIControlStateNormal];

    _recording = NO;
    
    //Do something useful with the video file available at the outputFileURL
    IDFileManager *fm = [IDFileManager new];
    [fm copyFileToCameraRollNew:outputFileURL];
    
    
    //Dismiss camera (when user taps cancel while camera is recording)
    if(_dismissing){
        [self stopPipelineAndDismiss];
    }
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
